package org.lib.authservice.user;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import lombok.Data;

/**
 * 用户
 * @author ben
 * @date 2021-10-21 14:36:14 CST
 */
@Entity
@Data
public class User implements UserDetails, Serializable {

	//
	// 字段

	private static final long serialVersionUID = 211021L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	@Column(nullable = false, unique = true)
	private String username;
	
	@Column
	private String password;

	@Column(insertable = false, columnDefinition = "DATETIME DEFAULT NOW()")
	private Date createTime;

	@Column(insertable = false, updatable = false, columnDefinition = "DATETIME DEFAULT NOW() ON UPDATE NOW()")
	private Date updateTime;
	
	//
	// 表关联
	
	// 1、默认的
//	@ManyToMany
	// 2、下面是书上的，EAGER？
	@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinTable(
			name="user_role_rel",
			joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id", 
					foreignKey = @ForeignKey(name="fk_urr_user")),
			inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id",
					foreignKey = @ForeignKey(name="fk_urr_role"))
			)
	private List<Role> authorities;
	
	//
	// 重写接口的方法
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	@Override
	public String getPassword() {
		return this.password;
	}

	@Override
	public String getUsername() {
		return this.username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}
